package com.akami.news;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import xframe.ctl.XDispatchAction;
import xframe.util.UtilMaster;
import xframe.util.db.Row;
import xframe.util.db.Transaction;

import java.util.*;

public class NewsPublishAction extends XDispatchAction {
	public ActionForward move( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception { 

		Row	req			=	getRequestInfo(request);
		
		
		
		
		return mapping.findForward((String) req.get("NEXT_PAGE") );
	}
	
	// 리스트
	public ActionForward selectPublishNews( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {

		Row	req			=	getRequestInfo(request);
			

		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			HttpSession session = request.getSession();
			req.put("s_name", session.getAttribute("name"));
			req.put("s_email", session.getAttribute("email"));
			
	        // 전체 게시물 갯수
			String totalQueryName	=	"newsMaster.publishNewsTotal";		
			String	totalQuery 	=	mappingQuery(request, totalQueryName);
			
			simpleExecuteQueryGetOneRow(request, totalQuery, totalQueryName);
			
			Row	SUM_LIST	=	(Row)request.getAttribute(totalQueryName);			
			req.put("TOTAL", SUM_LIST.getString("TOTAL"));					
			int start_row 	=	0;
			int page		=	0;
			//페이지 파라미터 점검
			//첫페이지는 파라미터가 없으므로 0이나 1로 셋팅한다.
			if(req.get("page") ==null || ((String)req.get("page")).trim().length() == 0 ){
				page	=	1;
			}else  {
				try{
					page	=	Integer.parseInt(((String)req.get("page")));
				}catch(Exception e){
					page	=	1;
				}
			}
			start_row	=	(page	-	1)	*	10;
			req.put("start_row", start_row+"");
			req.put("page", page+"");
			
			//전체게시물의 갯수를 토대로 다시 쿼리를 날려서 원하는 데이터만 받아온다.		
			String 	listQueryName	=	"newsMaster.publishNews";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
	
			simpleExecuteQuery(request, listQuery, listQueryName);												
			//전체게시물의 갯수를 토대로 다시 쿼리를 날려서 원하는 데이터만 받아온다.		
			 //	listQueryName	=	"newsMaster.linkKeyword";
				//listQuery 		=	mappingQuery(req, listQueryName);	
			
			//simpleExecuteQuery(request, listQuery, listQueryName);												
	
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.toString());
			return mapping.findForward( "system_error" );
		}        
		
        return mapping.findForward( "select" );       
	}
	
	
	// 발행 작성모드
	public ActionForward readyPub( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		
		
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
		
			//전체게시물의 갯수를 토대로 다시 쿼리를 날려서 원하는 데이터만 받아온다.		
			String 	listQueryName	=	"newsMaster.notPublishNewsList";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			
			simpleExecuteQuery(request, listQuery, listQueryName);												
			
			//디비연결 종
			Transaction.end(request);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.toString());
			return mapping.findForward( "system_error" );
		}        
		
		return mapping.findForward( "readyPub" );       
	}
	
	
	
	
	public ActionForward getPublish( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
			Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			String 	listQueryName	=	"newsMaster.getPublish";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			Row resultRow = simpleExecuteQueryGetOneRow(request, listQuery, listQueryName);												
	        
			String publish_code = resultRow.getString("publish_code");
			
			if(publish_code.equalsIgnoreCase("A0NWC0")){
				listQueryName	=	"newsMaster.getPublishLinkedNewsComplete";
				listQuery 		=	mappingQuery(req, listQueryName);
				simpleExecuteQuery(request, listQuery, "newsMaster.getPublishLinkedNewsS");
			}else{
				listQueryName	=	"newsMaster.getPublishLinkedNewsS";
				listQuery 		=	mappingQuery(req, listQueryName);
				simpleExecuteQuery(request, listQuery, listQueryName);
			}
			

															
			
			
			request.setAttribute("resultRow",resultRow);
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}    		
	return mapping.findForward("getPublish");
	}
	
	
	public ActionForward setDailyNews( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
		// 디비연결 시작
		Transaction.start(request);		
		
		HttpSession session = request.getSession();
		req.put("reg_email", session.getAttribute("s_email"));
		req.put("upd_email", session.getAttribute("s_email"));
		req.put("upd_tel", session.getAttribute("s_tel"));
		

		String queryName	=	"newsMaster.new_publish";		
		String publish_idx		=	System.nanoTime()+"";
		req.put("publish_idx",publish_idx);
		
		String	query 	=	mappingQuery(req, queryName);
		String[] preparedIndex = {
				"publish_idx",            
				"title",            
				"pub_date",            
				"content_html",            
				"publisher_email",            
				"publisher_name", 
				"upd_email", 
				"reg_name", 
				"reg_email", 
				"reg_name", 
				"publish_code"
				};
		//PreparedStatement  실행
		preparedExecuteUpdate(request, req, preparedIndex, query);	
		
		
		queryName	=	"newsMaster.linkUpdate";	
		
		 if (req.get("news_idx") instanceof String) {
				query 	=	mappingQuery(req, queryName);
				simpleExecuteUpdate(request, query, queryName);				
				
			}else{
				String[] news_idx = (String[])req.get("news_idx");
				for(int i =0 ; i < news_idx.length ; i++){
					req.put("news_idx",news_idx[i]);
					query 	=	mappingQuery(req, queryName);
					simpleExecuteUpdate(request, query, queryName);
				}
			}
		
		request.setAttribute("nextPage", request.getContextPath()+"/pub.do?command=selectPublishNews");

		
		session = request.getSession();
		req.put("s_name", session.getAttribute("name"));
		req.put("s_email", session.getAttribute("email"));
		
        // 전체 게시물 갯수
		String totalQueryName	=	"newsMaster.publishNewsTotal";		
		String	totalQuery 	=	mappingQuery(request, totalQueryName);
		
		simpleExecuteQueryGetOneRow(request, totalQuery, totalQueryName);
		
		Row	SUM_LIST	=	(Row)request.getAttribute(totalQueryName);			
		req.put("TOTAL", SUM_LIST.getString("TOTAL"));					
		int start_row 	=	0;
		int page		=	0;
		//페이지 파라미터 점검
		//첫페이지는 파라미터가 없으므로 0이나 1로 셋팅한다.
		if(req.get("page") ==null || ((String)req.get("page")).trim().length() == 0 ){
			page	=	1;
		}else  {
			try{
				page	=	Integer.parseInt(((String)req.get("page")));
			}catch(Exception e){
				page	=	1;
			}
		}
		start_row	=	(page	-	1)	*	10;
		req.put("start_row", start_row+"");
		req.put("page", page+"");
		
		//전체게시물의 갯수를 토대로 다시 쿼리를 날려서 원하는 데이터만 받아온다.		
		String 	listQueryName	=	"newsMaster.publishNews";
		String	listQuery 		=	mappingQuery(req, listQueryName);	

		simpleExecuteQuery(request, listQuery, listQueryName);			
        Transaction.end(request);
        
        
												
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		} 
		
		return mapping.findForward("sendRedirect");
	}
	
	
	public ActionForward updateDailyNews( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
			// 디비연결 시작
			Transaction.start(request);		
			
			HttpSession session = request.getSession();
			req.put("reg_email", session.getAttribute("s_email"));
			req.put("upd_email", session.getAttribute("s_email"));
			req.put("upd_tel", session.getAttribute("s_tel"));
			
			
			String queryName	=	"newsMaster.updateDailyNews";		
			
			String	query 	=	mappingQuery(req, queryName);

			String[] preparedIndex = {
					"title",            
					"pub_date",            
					"content_html",            
					"upd_email",            
					"upd_name",            
					"publish_code",       
					"publish_idx"       
			};
			
			//PreparedStatement  실행
			preparedExecuteUpdate(request, req, preparedIndex, query);	
			
			
			queryName	=	"newsMaster.deleteLinkedNews";	
			query 	=	mappingQuery(req, queryName);
			simpleExecuteUpdate(request, query, queryName);
			
			
			
			queryName	=	"newsMaster.linkUpdate";	
			
			
			
			
			 if (req.get("news_idx") instanceof String) {
					query 	=	mappingQuery(req, queryName);
					simpleExecuteUpdate(request, query, queryName);				
					
				}else{
					String[] news_idx = (String[])req.get("news_idx");
					for(int i =0 ; i < news_idx.length ; i++){
						req.put("news_idx",news_idx[i]);
						query 	=	mappingQuery(req, queryName);
						simpleExecuteUpdate(request, query, queryName);
					}
				}
			

			
			request.setAttribute("nextPage", request.getContextPath()+"pub.do?command=selectPublishNews");
			
			//디비연결 종
			Transaction.end(request);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		} 
		
		return mapping.findForward("sendRedirect");
	}
	
	public ActionForward select( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
			Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			String listQueryName		=	"newsMaster.select";		
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);												
	
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			System.out.println("******"+e.getMessage());
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}
		
		
		
		return mapping.findForward("select");
	}
	
	
	public ActionForward preview( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			String 	listQueryName	=	"newsMaster.getPublishPreview";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			Row resultRow = simpleExecuteQueryGetOneRow(request, listQuery, listQueryName);												
	        
			
			listQueryName	=	"newsMaster.getPublishLinkedNewsSpreview";
			listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);	
			
			ArrayList linkedNewsList	= (ArrayList)request.getAttribute(listQueryName);
			Row linkedKeyword		=	new Row();
			String	news_idx = "";
			StringBuffer	temp_keyword = null;
			ArrayList keywordList	= 	null;
			Row LikedNews = new Row();
			Row keyword	=	null;
			for(int i =0; i < linkedNewsList.size() ;i++){
				LikedNews = (Row)linkedNewsList.get(i);
				news_idx =LikedNews.getString("news_idx");
				req.put("news_idx", news_idx);
				listQueryName	=	"newsMaster.getKeyword";
				listQuery 		=	mappingQuery(req, listQueryName);	
				simpleExecuteQuery(request, listQuery, listQueryName);
				keywordList	= (ArrayList)request.getAttribute(listQueryName);
				temp_keyword = new StringBuffer("");
				for(int k=0 ; k < keywordList.size();k++){
					temp_keyword.append(((Row)keywordList.get(k)).get("keyword")).append(", ");
				}
				linkedKeyword.put(news_idx, temp_keyword.toString().trim());
			}
			request.setAttribute("linkedKeyword", linkedKeyword);
			
			request.setAttribute("resultRow",resultRow);
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}    	
		
		return mapping.findForward("preview");
	}
	
	public ActionForward codeDelete( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		return mapping.findForward("selectCode");
	}
}
